<?php
/**
 * 物资明细，库存
 */
namespace App\Http\Controllers\Api;
use App\Model\Users;
use App\Model\WarehouseOutboundDetail;
use App\Model\Stock;
use App\Model\MaterialList;
use App\Model\WarehouseMaterials;
use App\Model\Checkcategory;
use App\Model\Company;
use App\Model\WarehouseOrder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StockController extends Controller
{
    /**
     * 物资库存管理跟明细列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stocklistdata(Request $request)
    {
        $query = $this->stockpub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        /*foreach ($res['data'] as $key=>$val){
            if(empty($val['company'])){
                unset($res['data'][$key]);
            }
            if(empty($val['material_list'])){
                unset($res['data'][$key]);
            }
        }*/
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * 物资明细列表数据操作pc端出库修改时用到
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stocklistdatatoadd(Request $request)
    {
        $query = $this->stockpub($request);
        $res['stock']=$query->get()->toArray();
        /*foreach ($res['data'] as $key=>$val){
            if(empty($val['company'])){
                unset($res['data'][$key]);
            }
            if(empty($val['material_list'])){
                unset($res['data'][$key]);
            }
        }*/
        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'data'  => $res
        ];
        return response()->json($data);
    }

    /**
     * 导出物资库存管理跟明细列表
     * @param $request
     * @return array
     */
    public function stockpub($request){
//        $a=Stock::find(1);
//        dd($a->warehouseMaterials->toArray());
        $user = Auth::user();
        $role = $user->role;
        $community = $user->community;

        $comName = $request['comname']??''; //单位名称搜索
        $name = $request['name']??'';
        $query= Stock::with([
            //'warehouseMaterials:material_id,id,unit',
            'checkcategory:id,name',
            'goods:id,name',
            'materialList:id,name',    //物资名称
            'company:id,comName,address,leader,leaderPhone,community',
        ])->whereHas('materialList' , function ($q) use ($name) {
            $q->select('id','name');
            if($name){
                $q->where('name', 'like','%'.$name.'%');
            }

        })->whereHas('company' , function ($q) use ($comName) {
            if($comName){
                $q->where('comName', 'like','%'.$comName.'%');
            }
        })->where('goods_id','!=',0)->where('material_id','!=',0)->where('checkcategory_id','!=',0)->where('company_id','!=',0)  ;   //
        if(Users::iscommunity($role)){
            $query = $query->whereHas('company', function ($q) use ($community) {
                $q->where('community', $community);
            });
        }
        if(isset($request['goods_id']) && $goods_id = $request['goods_id']){ //分类名称
            $query = $query->where('goods_id',$goods_id);
        }
        if(isset($request['checkcategory_id']) && $checkcategory_id = $request['checkcategory_id']){  //所属单位
            $query = $query->where('checkcategory_id',$checkcategory_id);
        }
        if(isset($request['material_id']) && $material_id = $request['material_id']){  //物资id
            $query = $query->where('material_id',$material_id);
        }
        if(isset($request['company_id']) && $company_id = $request['company_id']){  //单位名称
            $query = $query->where('company_id',$company_id);
        }
        if(isset($request['status']) && $status = $request['status']){  //状态
            // ['1'=>'在库','2'=>'出库','3'=>'损耗'] 在库是库存有值，出库是库存为0，损耗是损耗数量是有值？这样区分的状态？
            if($status==1){
                $query = $query->where('warehouse','!=','0');
            }elseif ($status==2){
                $query = $query->where('warehouse','0');
            }elseif ($status==3){
                $query = $query->where('loss_warehouse','!=','0');
            }
        }
        return $query;
    }

    /**
     * 导出物资库存管理跟明细列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function stockexportone(Request $request)
    {
        $query = $this->stockpub($request);
        $dataExpor= $query->get()->toArray();
        $data = [];
        foreach ($dataExpor as $key=>$val){
            if(isset($val['company']) && $val['company']){
                $val['checkcategory_name'] = $val['checkcategory']['name'];
                $val['goods_name'] = $val['goods']['name']??'';
                $val['material_list_name'] = $val['material_list']['name']??'';
                $val['company_name'] = $val['company']['comName']??'';
                $val['address'] = $val['company']['address']??'';
                $val['leader'] = $val['company']['leader']??'';
                $val['leaderPhone'] = $val['company']['leaderPhone']??'';
                $data[]=$val;
            }
        }

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I','J','K','L');
        $title = [
            'A1'=>'序 号',
            'B1'=>'所属单位（人）',
            'C1'=>'单位（个人）名称',
            'D1'=>'物资分类',
            'E1'=>'物资名称',
            'F1'=>'入库数量',
            'G1'=>'库存数量',
            'H1'=>'出库数量',
            'I1'=>'损耗数量',
            'J1'=>'具体位置',
            'K1'=>'联系人',
            'L1'=>'联系电话',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($data as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['checkcategory_name']??'');
            $objActSheet->setCellValue("C".$orirow,$val['company_name']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['material_list_name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['income_warehouse']??'');
            $objActSheet->setCellValue("G".$orirow,$val['warehouse']??'');
            $objActSheet->setCellValue("H".$orirow,$val['leave_warehouse']??'');
            $objActSheet->setCellValue("I".$orirow,$val['loss_warehouse']??'');
            $objActSheet->setCellValue("J".$orirow,$val['address']??'');
            $objActSheet->setCellValue("K".$orirow,$val['leader']??'');
            $objActSheet->setCellValue("L".$orirow," ".$val['leaderPhone']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:L1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资明细表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 物资流向
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function materials_trend(Request $request)
    {
        $stock_id = isset($request['stock_id']) ? $request['stock_id'] : 0; //明细id
        /*$goods_id = isset($request['goods_id']) ? $request['goods_id'] : 0;
        $material_id = isset($request['material_id']) ? $request['material_id'] : 0;
        $checkcategory_id = isset($request['checkcategory_id']) ? $request['checkcategory_id'] : 0;
        $company_id = isset($request['company_id']) ? $request['company_id'] : 0;*/
        //$materialList = MaterialList::with(['goods:id,name',])->where('id',$material_id)->first();
        $stock= Stock::with([
            //'warehouseMaterials:material_id,id,unit',
            'checkcategory:id,name',
            'goods:id,name',
            'materialList:id,name',
            'company:id,comName,address,leader,leaderPhone'])->where('id',$stock_id)->first();   //where('goods_id',$goods_id)->where('material_id',$material_id)->where('checkcategory_id',$checkcategory_id)->where('company_id',$company_id)
        if(empty($stock)){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该物资流向不存在，请联系管理员';
            return response()->json($res_arr);
        }
        $goods_id = $stock->goods_id ?? 0;
        $material_id = $stock->material_id ?? 0;
        $checkcategory_id = $stock->checkcategory_id ?? 0;
        $company_id = $stock->company_id ?? 0;
        //新增入库
        $newly_increased = WarehouseMaterials::with(['Users:id,name'])->select('created_at','number','applicant','user_id')->where('goods_id',$goods_id)->where('material_id',$material_id)->where('checkcategory_id',$checkcategory_id)->where('company_id',$company_id)->whereIn('warehouse_type', [1,2])->get()->toArray();
        //归还入库
        $revert = WarehouseMaterials::with(['Users:id,name'])->select('created_at','number','applicant','user_id')->where('goods_id',$goods_id)->where('material_id',$material_id)->where('checkcategory_id',$checkcategory_id)->where('company_id',$company_id)->where('warehouse_type', 3)->get()->toArray();
        //出库
        $outbound = WarehouseOutboundDetail::getOutMaterialBysid($stock_id,[1,2]);
        //报废
        $scrap = WarehouseOutboundDetail::getOutMaterialBysid($stock_id,[3]);

        $res_arr['data']['stock_data'] = $stock;
        $res_arr['data']['newly_increased'] = $newly_increased;
        $res_arr['data']['revert'] = $revert;
        $res_arr['data']['outbound'] = $outbound;
        $res_arr['data']['scrap'] = $scrap;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资流向导出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function trend_exportone(Request $request)
    {
        $data = $this->materials_trend($request);
        $data = json_decode(json_encode($data), true);
        $original = $data['original']??[];
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("excel/trend_exportone.xlsx");
        $objPHPExcel->createSheet();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("物资流向表");
        $objActSheet = $objPHPExcel->getActiveSheet();

        $row = 2;
        $i = 1;
        //物资详情
        $tt = $original['data']['stock_data'];
        $objPHPExcel->getActiveSheet()->setCellValue("A".$row,$tt['material_list']['name']);
        $objPHPExcel->getActiveSheet()->setCellValue("B".$row,$tt['goods']['name']);
        $objPHPExcel->getActiveSheet()->setCellValue("C".$row,$tt['income_warehouse']);
        $objPHPExcel->getActiveSheet()->setCellValue("D".$row,$tt['warehouse']);
        $objPHPExcel->getActiveSheet()->setCellValue("E".$row,$tt['leave_warehouse']);
        $objPHPExcel->getActiveSheet()->setCellValue("F".$row,$tt['loss_warehouse']);
        $objPHPExcel->getActiveSheet()->setCellValue("G".$row,$tt['unit']);
        $objPHPExcel->getActiveSheet()->setCellValue("H".$row,$tt['checkcategory']['name']);
        $objPHPExcel->getActiveSheet()->setCellValue("I".$row,$tt['company']['comName']);
        $objPHPExcel->getActiveSheet()->setCellValue("J".$row,$tt['company']['address']);
        $objPHPExcel->getActiveSheet()->setCellValue("O".$row,$tt['company']['leader']);
        $objPHPExcel->getActiveSheet()->setCellValue("P".$row,$tt['company']['leaderPhone']);
        $row_nt=$row_ot=$row_rt=$row_st=6;
        //物资流向-入库
        foreach($original['data']['newly_increased'] as $nt)
        {
            $objPHPExcel->getActiveSheet()->setCellValue("A".$row_nt,$i);
            $objPHPExcel->getActiveSheet()->setCellValue("B".$row_nt,$nt['created_at']);
            $objPHPExcel->getActiveSheet()->setCellValue("C".$row_nt,$nt['number']);
            $objPHPExcel->getActiveSheet()->setCellValue("D".$row_nt,$nt['users']['name']??'');
            $row_nt++;
            $i++;
        }
        //物资流向-出库
        foreach($original['data']['outbound'] as $ot)
        {
            $objPHPExcel->getActiveSheet()->setCellValue("E".$row_ot,$ot['created_at']);
            $objPHPExcel->getActiveSheet()->setCellValue("F".$row_ot,$ot['number']);
            $objPHPExcel->getActiveSheet()->setCellValue("G".$row_ot,$ot['warehouse_outbound']['cause']);
            $objPHPExcel->getActiveSheet()->setCellValue("H".$row_ot,$ot['warehouse_outbound']['applicant']);
            $objPHPExcel->getActiveSheet()->setCellValue("I".$row_ot,$ot['warehouse_outbound']['users']['name']??'');
            $row_ot++;
        }
        //物资流向-归还
        foreach($original['data']['revert'] as $rt)
        {
            $objPHPExcel->getActiveSheet()->setCellValue("J".$row_rt,$rt['created_at']);
            $objPHPExcel->getActiveSheet()->setCellValue("K".$row_rt,$rt['number']);
            $objPHPExcel->getActiveSheet()->setCellValue("L".$row_rt,$rt['applicant']);
            $objPHPExcel->getActiveSheet()->setCellValue("M".$row_rt,$rt['users']['name']??'');
            $row_rt++;
        }
        //物资流向-报废
        foreach($original['data']['scrap'] as $st)
        {
            $objPHPExcel->getActiveSheet()->setCellValue("N".$row_st,$st['created_at']);
            $objPHPExcel->getActiveSheet()->setCellValue("O".$row_st,$st['number']);
            $objPHPExcel->getActiveSheet()->setCellValue("P".$row_st,$st['warehouse_outbound']['users']['name']??'');
            $row_st++;
        }

        for ($x=1; $x<=5; $x++) {
            if($x==3){
                $objActSheet->getRowDimension($x)->setRowHeight(33);//统一设置行高度
            }else{
                $objActSheet->getRowDimension($x)->setRowHeight(25);//统一设置行高度
            }
        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        //$objActSheet->getStyle('A1:E'.($row+10))->applyFromArray($styleArray);//设置粗边框
        //$objActSheet->getRowDimension(1)->setRowHeight(30);//单独设置行高度
        $write = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        /*header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="物资流向表.xls"');//可以让浏览器弹出下载窗口
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');*/
        $date=time();
        $filename = '物资流向表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 获取所有所属单位适用于下拉列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkcategory_all(Request $request)
    {
        $checkcategory = Checkcategory::select('id','name')->get()->toArray(); //所属单位
        $res_arr['data'] = $checkcategory;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 获取所有单位名称适用于下拉列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function company_all(Request $request)
    {
        $companys = Company::select('id','comName','address');
        $user = Auth::user();
        $role = $user->role;
        $community = $user->community;
        if(Users::iscommunity($role)){
            $companys = $companys->where('community',$community);
        }
        if(isset($request['checkcategory_id']) && $checkcategory_id = $request['checkcategory_id']){ //所属单位id
            $companys = $companys->where('categoryId',$checkcategory_id);
        }

        $companys = $companys->get()->toArray(); //单位名称
        $res_arr['data'] = $companys;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 获取所有状态适用于下拉列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function status_all(Request $request)
    {
        $get_status = Stock::get_status(); //状态
        $res_arr['data'] = $get_status;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 通过id获取物资详情
     * @param $request
     * @return array
     */
    public function getdetailall(Request $request){
//        $a=Stock::find(1);
//        dd($a->warehouseMaterials->toArray());
        $ids = $request['ids']??[]; //明细id
        $id_arr = explode(',',$ids);
        $res= Stock::with([
            //'warehouseMaterials:material_id,id,unit',
            'checkcategory:id,name',
            'goods:id,name',
            'materialList:id,name',
            'company:id,comName,address,leader,leaderPhone',
        ])->whereIn('id',$id_arr)->get()->toArray();

        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'data'  => $res
        ];
        return response()->json($data);
    }

    /**
     * 通过goods_id，material_id，checkcategory_id，company_id获取物资明细id
     * @param $request
     * @return array
     */
    public function getstockid(Request $request){
//        $a=Stock::find(1);
//        dd($a->warehouseMaterials->toArray());
        $goods_id = $request['goods_id']; //goods_id
        $material_id = $request['material_id']; //goods_id
        $checkcategory_id = $request['checkcategory_id']; //goods_id
        $company_id = $request['company_id']; //goods_id
        $res= Stock::where('goods_id',$goods_id)->where('material_id',$material_id)->where('checkcategory_id',$checkcategory_id)->where('company_id',$company_id)->first();

        $data = [
            'code' => 200,
            'msg'   => '请求成功',
            'data'  => $res
        ];
        return response()->json($data);
    }
}
